package com.company.admin.common.interceptor;

import com.company.admin.common.annotations.VisitAble;
import com.company.admin.common.myException.BizException;
import com.company.admin.entity.User.AdminUserEntity;
import com.company.admin.service.user.UserService;
import com.fasterxml.jackson.databind.cfg.HandlerInstantiator;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.beans.Visibility;

/**
 * @author 赵成林
 * @date 2019/2/16 21:34
 * 拦截器
 * 解决跨域
 * 验证登录信息
 */
@Component
public class UserAccessInterceptor implements HandlerInterceptor {

    @Autowired
    private UserService userService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 前后端分离，解决跨域
        response.setHeader("Access-Control-Allow-Origin", request.getHeader("Origin"));
        response.setHeader("Access-Control-Allow-Credentials", "true");
        response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
        response.setHeader("Access-Control-Max-Age", "3600");
        response.setHeader("Access-Control-Allow-Headers", "Content-Type,Accept,X-Requested-With,token");

        // 验证用户的登录信息
        String token = request.getHeader("token");
        if (StringUtils.isNotEmpty(token)){
            // 验证token是否有效
            AdminUserEntity adminUserEntity = userService.getUserByToken(token);
            if (adminUserEntity == null){
                throw new BizException(201, "无效的登录信息，请重新登录");
            }
        } else {
            if (handler instanceof HandlerMethod){
                HandlerMethod handlerMethod = (HandlerMethod) handler;
                VisitAble visitAble = handlerMethod.getMethodAnnotation(VisitAble.class);
                if (visitAble != null){
                    return true;
                }
                if (!handlerMethod.getMethod().getName().toUpperCase().equals("LOGIN")){
                    throw new BizException(201, "需要登录才能访问");
                }
            }
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable Exception ex) throws Exception {

    }
}
